package com.example.fechat.fragment

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.fechat.R
import com.example.fechat.activity.MessageActivity
import com.example.fechat.base.BaseAdapter
import com.example.fechat.room.user.UserDBUtils
import com.example.fechat.room.user.UserEntity
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import java.util.*

class ChatFragment : Fragment() {
    private var baseAdapter: BaseAdapter? = null
    private lateinit var recyclerView: RecyclerView
    private var data: List<UserEntity>? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_chat, container, false)

        recyclerView = view.findViewById(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(context)

        data =
            ArrayList(UserDBUtils.getAll(context)).filter { it.last_message.isNotEmpty() }
        data?.let {
            Collections.sort(it) { o1, o2 ->
                (o2.duration - o1.duration).toInt()
            }
        }
        baseAdapter = BaseAdapter(data!!)
        recyclerView.adapter = baseAdapter
        baseAdapter?.setOnItemClickListener(object : BaseAdapter.OnItemClickListener {
            override fun onItemClick(view: View, position: Int) {
                val intent = Intent(context, MessageActivity::class.java)
                intent.putExtra("UserInfo", data!![position].toString())
                startActivity(intent)
            }
        })
        return view
    }

    fun resume() {
        if(context == null)
            return
        data =
            ArrayList(UserDBUtils.getAll(context)).filter { it.last_message.isNotEmpty() }
        data?.let {
            Collections.sort(it) { o1, o2 ->
                (o2.duration - o1.duration).toInt()
            }
        }
        baseAdapter?.setNewData(data!!)
    }
}